package pzl.com.androidloader.loader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.AsyncTaskLoader;

import java.io.IOException;
import java.net.URL;

/**
 * @author zl.peng
 * @version [1.0, 2016-10-24]
 */
public class ImageTaskLoader extends AsyncTaskLoader<Bitmap> {
    private IGetDataSource iGetDataSource;

    public ImageTaskLoader(Context context) {
        super(context);
    }

    public ImageTaskLoader(Context context, IGetDataSource iGetDataSource) {
        super(context);
        this.iGetDataSource = iGetDataSource;
    }

    @Override
    public Bitmap loadInBackground() {
        Bitmap bitmap = null;
        String url = iGetDataSource.getImageUrlSource();
        try {
            bitmap = BitmapFactory.decodeStream(new URL(url).openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    public void deliverResult(Bitmap data) {
        super.deliverResult(data);
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        forceLoad();
    }

    @Override
    protected void onStopLoading() {
        super.onStopLoading();
        cancelLoad();
    }

    @Override
    protected void onReset() {
        super.onReset();
    }

    /**
     * 获得loader观察的数据源的参数
     */
    public interface IGetDataSource {
        String getImageUrlSource();
    }


}
